<template>
  <div class="order-create">
    <h1>创建订单</h1>
    <div class="form-container">
      <el-form :model="orderForm" :rules="rules" ref="orderForm" label-width="100px">
        <el-form-item label="工单标题" prop="title">
          <el-input v-model="orderForm.title" />
        </el-form-item>
        <el-form-item label="联系人" prop="name">
          <el-select 
            v-model="orderForm.name" 
            placeholder="请选择或输入联系人" 
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="fetchCustomers"
            :loading="customerLoading"
            @change="onCustomerSelect"
            @focus="loadCustomerList"
          >
            <el-option
              v-for="customer in customerList"
              :key="customer.id"
              :label="customer.customerName"
              :value="customer.customerName">
              <span style="float: left">{{ customer.customerName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="orderForm.phone" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="orderForm.address" placeholder="请输入地址或点击右侧按钮选择地图">
            <template #append>
              <el-button icon="el-icon-location" @click="showMapDialog">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="orderForm.des" type="textarea" />
        </el-form-item>
        <el-form-item label="工单类型">
          <el-select v-model="orderForm.type" placeholder="请选择工单类型">
            <el-option label="普通" :value="0"></el-option>
            <el-option label="紧急" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联商品">
          <el-select 
            v-model="orderForm.productId" 
            placeholder="请选择关联商品（可选）" 
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="fetchProducts"
            :loading="productLoading"
            @focus="loadProductList"
          >
            <el-option
              v-for="product in productList"
              :key="product.id"
              :label="product.productName"
              :value="product.id">
              <span style="float: left">{{ product.productName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">¥{{ product.price }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">创建订单</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 地图选择对话框 -->
    <el-dialog title="选择地址" v-model="mapDialogVisible" width="60%" :before-close="handleMapDialogClose">
      <MapContainer ref="mapContainer" @location-selected="onLocationSelected" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="mapDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmLocation">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addOrderAPI } from '@/apis/order'
import { getProductListAPI } from '@/apis/supplier'
import { getCustomerInfoAPI } from '@/apis/user'
import MapContainer from './MapContainer.vue'

export default {
  name: 'OrderCreate',
  components: {
    MapContainer
  },
  data() {
    return {
      orderForm: {
        title: '',
        name: '',
        phone: '',
        address: '',
        des: '',
        type: 1,
        status: 0,
        payStatus: 0,
        productId: null,
        customerId: null,
        latitude: null,
        longitude: null
      },
      rules: {
        title: [
          { required: true, message: '请输入工单标题', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ]
      },
      productList: [],
      allProducts: [], // 存储所有商品
      productLoading: false,
      customerList: [],
      allCustomers: [], // 存储所有客户
      customerLoading: false,
      // 地图对话框控制
      mapDialogVisible: false,
      selectedLocation: null
    }
  },
  created() {
    // 组件创建时加载商品列表和客户列表
    this.loadProductList()
    this.loadCustomerList()
  },
  methods: {
    showMapDialog() {
      this.mapDialogVisible = true
    },
    
    handleMapDialogClose() {
      this.mapDialogVisible = false
      this.selectedLocation = null
    },
    
    onLocationSelected(location) {
      this.selectedLocation = location
    },
    
    confirmLocation() {
      if (this.selectedLocation) {
        this.orderForm.address = this.selectedLocation.address || ''
        this.orderForm.latitude = this.selectedLocation.latitude || null
        this.orderForm.longitude = this.selectedLocation.longitude || null
      }
      this.mapDialogVisible = false
    },
    
    async loadCustomerList() {
      // 加载所有客户列表
      this.customerLoading = true
      try {
        const res = await getCustomerInfoAPI()
        if (res.code === 0) {
          this.allCustomers = res.data || []
          this.customerList = this.allCustomers
        } else {
          this.$message.error(res.msg || '获取客户列表失败')
        }
      } catch (error) {
        this.$message.error('获取客户列表失败: ' + (error.msg || error.message || '未知错误'))
        console.error('获取客户列表失败:', error)
      } finally {
        this.customerLoading = false
      }
    },
    async fetchCustomers(query) {
      // 根据查询关键词筛选客户
      if (query !== '') {
        this.customerLoading = true
        try {
          // 在本地数据中搜索，而不是每次都调用API
          this.customerList = this.allCustomers.filter(customer => {
            return customer.customerName.toLowerCase().includes(query.toLowerCase()) || 
                   customer.phone.includes(query)
          })
        } catch (error) {
          this.$message.error('搜索客户失败: ' + (error.msg || error.message || '未知错误'))
          console.error('搜索客户失败:', error)
        } finally {
          this.customerLoading = false
        }
      } else {
        // 如果查询为空，显示所有客户
        this.customerList = this.allCustomers
      }
    },
    onCustomerSelect(customerName) {
      // 当客户选择改变时，只自动填充联系电话，不填充地址
      if (customerName) {
        const customer = this.allCustomers.find(c => c.customerName === customerName)
        if (customer) {
          this.orderForm.phone = customer.phone
          this.orderForm.customerId = customer.id
        }
      } else {
        // 清空客户选择时，只清空联系电话和客户ID
        this.orderForm.phone = ''
        this.orderForm.customerId = null
      }
    },
    async loadProductList() {
      // 加载所有商品或默认商品列表
      this.productLoading = true
      try {
        const params = {
          pageNo: 1,
          pageSize: 1000, // 加载更多商品
          bo: {}
        }
        
        const res = await getProductListAPI(params)
        if (res.code === 0) {
          this.allProducts = res.data?.records || []
          this.productList = this.allProducts
        } else {
          this.$message.error(res.msg || '获取商品列表失败')
        }
      } catch (error) {
        this.$message.error('获取商品列表失败: ' + (error.msg || error.message || '未知错误'))
        console.error('获取商品列表失败:', error)
      } finally {
        this.productLoading = false
      }
    },
    async fetchProducts(query) {
      // 根据查询关键词筛选商品
      if (query !== '') {
        this.productLoading = true
        try {
          // 在本地数据中搜索，而不是每次都调用API
          this.productList = this.allProducts.filter(product => {
            return product.productName.toLowerCase().includes(query.toLowerCase())
          })
        } catch (error) {
          this.$message.error('搜索商品失败: ' + (error.msg || error.message || '未知错误'))
          console.error('搜索商品失败:', error)
        } finally {
          this.productLoading = false
        }
      } else {
        // 如果查询为空，显示所有商品
        this.productList = this.allProducts
      }
    },
    submitForm() {
      this.$refs.orderForm.validate(async (valid) => {
        if (valid) {
          try {
            const orderData = { ...this.orderForm }
            // 如果没有选择商品，则移除 productId 字段
            if (!orderData.productId) {
              delete orderData.productId
            }
            
            // 如果没有选择客户，则移除 customerId 字段
            if (!orderData.customerId) {
              delete orderData.customerId
            }
            
            // 如果没有选择地址，则移除经纬度字段
            if (!orderData.latitude || !orderData.longitude) {
              delete orderData.latitude
              delete orderData.longitude
            }
            
            const res = await addOrderAPI(orderData)
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '创建订单成功!'
              })
              this.resetForm()
            } else {
              this.$message({
                type: 'error',
                message: res.msg || '创建订单失败'
              })
            }
          } catch (error) {
            this.$message({
              type: 'error',
              message: '创建订单失败: ' + (error.msg || error.message || '未知错误')
            })
            console.error('创建订单失败:', error)
          }
        }
      })
    },
    resetForm() {
      this.$refs.orderForm.resetFields()
      this.orderForm.type = 1
      this.orderForm.status = 0
      this.orderForm.payStatus = 0
      this.orderForm.productId = null
      this.orderForm.customerId = null
      this.orderForm.latitude = null
      this.orderForm.longitude = null
      // 重置商品列表为所有商品
      this.productList = this.allProducts
      // 重置客户列表为所有客户
      this.customerList = this.allCustomers
    }
  }
}
</script>

<style scoped>
.order-create {
  padding: 20px;
}

.form-container {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.address-name {
  font-weight: bold;
  margin-bottom: 2px;
}

.address-address {
  font-size: 12px;
  color: #8492a6;
}
</style>